package com.eascs.web.o2o.scheduler.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.badloan.entity.O2oCacleEntity;
import com.eascs.admin.o2o.badloan.service.ICancelService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.web.o2o.scheduler.dao.BaseDao;
import com.eascs.web.o2o.scheduler.dao.ServiceDao;
import com.eascs.web.o2o.scheduler.entity.BasicInformationLoanIng;
import com.eascs.web.o2o.scheduler.entity.O2oLoanapplyEntity;
import com.eascs.web.o2o.scheduler.entity.ReportLoanIng;
import com.eascs.web.o2o.scheduler.util.Constant;
import com.eascs.workflow.common.entity.wf.ProcessTaskNode;


@Service
public class ServiceService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Inject
	ServiceDao serviceDao;

	@Inject
	com.eascs.web.o2o.dc.dao.ServiceDao serviceDcDao;

	@Inject
	BaseDao baseDao;
	@Reference
	com.eascs.workflow.common.service.wf.WorkFlowService workflowService;
	@Reference
	ICancelService cancelService;

	/**
	 * 保存全部字段数据
	 * 
	 * @param sql
	 *            查询表语句
	 * @param requiredType
	 *            对象
	 * @param delSql
	 *            删除表语句
	 * 
//	 */
//	public <T> void loadData(String sql, Class<T> requiredType, String delSql) {
//		int index = 0;
//		int total = 0;
//		while (index >= 0) {
//			SqlPageQuery<T> sqlPageQuery = new SqlPageQuery<>(requiredType, Constant.PROCESS_DATA_LIMIT, index, sql);
//			PageResult<T> pageResult = this.serviceDao.findDataWithPage(sqlPageQuery);
//			if (pageResult.getReturnDataSize() == 0)
//				return;
//			Integer count = pageResult.getDbRowCount();
//			if (index == 0 && count > 0) {
//				if (!"".equals(delSql)) {
//					// 有数据先清空该表数据
//					serviceDao.deleteEntity(delSql);
//				}
//			}
//			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
//				T obj = pageResult.getData().get(i);
//				logger.debug("total:{},{}", ++total, obj.toString());
//				try {
//
//					serviceDao.saveEntity(obj);
//				} catch (Exception e) {
//					logger.error("数据库异常", e);
//
//				}
//			}
//
//			if (pageResult.getPageTotal() > index + 1) {
//				index++;
//			} else {
//				index = -1;
//			}
//		}
//
//	}

	/**
	 * 同步数据字典PubDatadictionary
	 */
	public void loadPubDatadictionary() {
		String sql = "SELECT * from eadb.pub_datadictionary order by ddno";
		int index = 0;
		while (index >= 0) {
			SqlPageQuery<com.eascs.web.o2o.report.entity.PubDatadictionary> sqlPageQuery = new SqlPageQuery<>(com.eascs.web.o2o.report.entity.PubDatadictionary.class, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<com.eascs.web.o2o.report.entity.PubDatadictionary> pageResult = this.baseDao.findDataWithPage(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				com.eascs.web.o2o.report.entity.PubDatadictionary pubDatadictionary = pageResult.getData().get(i);
				try {
					int count = serviceDcDao.updateById(pubDatadictionary);
					if (count <= 0) {
						serviceDao.saveEntity(pubDatadictionary);
					}
				} catch (Exception e) {
					logger.error("数据库异常", e);
				}
			}
			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}
	}

	/**
	 * 同步数据字典PubDditem
	 */
	public void loadDataPubDditem() {
		String sql = "SELECT itemno as item_no,itemcode as item_code,itemname as item_name,itemorder as item_order,ddno as dd_no,islock as is_lock,issync as is_sync,parentno from eadb.pub_dditem order by itemno";
		int index = 0;
		while (index >= 0) {
			SqlPageQuery<com.eascs.web.o2o.report.entity.PubDditem> sqlPageQuery = new SqlPageQuery<>(com.eascs.web.o2o.report.entity.PubDditem.class, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<com.eascs.web.o2o.report.entity.PubDditem> pageResult = this.baseDao.findDataWithPage(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				com.eascs.web.o2o.report.entity.PubDditem pubDditem = pageResult.getData().get(i);
				try {
					int count = serviceDcDao.updateById(pubDditem);
					if (count <= 0) {
						serviceDao.saveEntity(pubDditem);
					}
				} catch (Exception e) {
					logger.error("数据库异常", e);
				}
			}
			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}
	}

	/**
	 * 更新或者插入表部分数据
	 * 
	 * @param sql
	 *            查询sql语句
	 * @param delSql
	 *            删除sql语句
	 * @param exeSql
	 *            执行更新或者添加的sql语句
	 */
	public void loadPartPartData(String sql, String delSql, String exeSql, String findEntitySql) {
		int index = 0;
		int total = 0;
		while (index >= 0) {
			SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<Object[]> pageResult = this.serviceDao.findDataWithPage(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			Integer count = pageResult.getDbRowCount();
			if (index == 0 && count > 0) {
				if (!"".equals(delSql)) {
					// 有数据先清空该表数据
					serviceDao.deleteEntity(delSql);
				}
			}
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] objs = pageResult.getData().get(i);

				logger.info("total:{},{}", ++total, objs);
				try {
					Integer flag = serviceDao.countMysql(findEntitySql, objs[1], objs[0]);
					if (flag == 0) {
						serviceDao.excuteSql(exeSql, objs[0], objs[1]);
					}
				} catch (Exception e) {
					logger.error("主键", objs[0]);
					logger.error("数据库异常", e);

				}
			}

			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}

	}

	/**
	 * @插入 sql
	 */
	public void excute(String sql, Object... params) {

		serviceDao.excuteSql(sql, params);

	}

	/**
	 * @Title: saveLoaningData
	 * @Description: 同步新系统的贷中数据
	 * @author 张庆奇
	 * @return void
	 * @throws @date
	 *             2016年9月21日 下午5:34:34
	 */
	public void saveLoaningData() {
		Calendar cal = Calendar.getInstance();
		String today = new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
		cal.add(Calendar.DATE, -1);
		String yesterday = new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
		int index = 0;
		while (index >= 0) {
			SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index,
					"select l.loanapply_no,wf_type,start_date from wf_type_status l where start_date>= DATE_FORMAT('" + yesterday + "', '%Y-%m-%d') AND start_date < DATE_FORMAT('" + today + "', '%Y-%m-%d')");
			PageResult<Object[]> pageResult = this.serviceDao.findDataWithPageForService(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] objs = pageResult.getData().get(i);
				BasicInformationLoanIng vo = new BasicInformationLoanIng();
				vo.setLoanapplyno(objs[0].toString());
				String type = objs[1].toString();
				Date date = DateUtils.formateStandDateTime(objs[2].toString());
				if ("ZX".equals(type)) {
					// 征信提交时间
					baseDao.excuteSql("update  basic_information_loan_ing set credit_reporting_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--征信提交时间：[{}]", vo.getLoanapplyno(), date);
				} else if ("NS".equals(type)) {
					// 内审提交时间
					baseDao.excuteSql("update  basic_information_loan_ing set in_exam_ing_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--内审提交时间：[{}]", vo.getLoanapplyno(), date);
				}
			}

			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}

		index = 0;
		while (index >= 0) {
			SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index,
					"select l.loanapply_no,wf_type,end_date from wf_type_status l where end_date>=DATE_FORMAT('" + yesterday + "', '%Y-%m-%d') AND end_date < DATE_FORMAT('" + today + "', '%Y-%m-%d')");
			PageResult<Object[]> pageResult = this.serviceDao.findDataWithPageForService(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] objs = pageResult.getData().get(i);
				BasicInformationLoanIng vo = new BasicInformationLoanIng();
				vo.setLoanapplyno(objs[0].toString());
				String type = objs[1].toString();
				Date date = DateUtils.formateStandDateTime(objs[2].toString());
				if ("ZX".equals(type)) {
					// 征信结束时间
					baseDao.excuteSql("update  basic_information_loan_ing set credit_over_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--征信结束时间：[{}]", vo.getLoanapplyno(), date);

				} else if ("NS".equals(type)) {
					// 内审结束时间
					baseDao.excuteSql("update  basic_information_loan_ing set in_exam_over_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--内审结束时间：[{}]", vo.getLoanapplyno(), date);

				} else if ("BRT".equals(type)) {
					// 银行送审结束时间
					baseDao.excuteSql("update  basic_information_loan_ing set bank_submit_over_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--银行送审结束时间：[{}]", vo.getLoanapplyno(), date);

				}

			}

			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}

		// 银行放款时间

		List<Object[]> list = serviceDao
				.findParams("select da.loan_date ,ly.loanapply_no from o2o_loanapply ly left join o2o_bank_loan_data  da  on ly.bill_code = da.bill_code where  da.loan_date>= DATE_FORMAT('" + yesterday + "', '%Y-%m-%d') AND da.loan_date < DATE_FORMAT('" + today + "', '%Y-%m-%d')");
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {

				Date date = DateUtils.formateStandDateTime(list.get(i)[0].toString() + " 00:00:00");
				String loanapplyno = list.get(i)[1].toString();
				baseDao.excuteSql("update  basic_information_loan_ing set bank_loan_date=? where loanapplyno=? ", date, loanapplyno);
				logger.info("新系统中的贷款数据（贷中）单号：[{}]--银行放款时间：[{}]", loanapplyno, date);
			}

		}

	}

	/**
	 * @Title: saveLoaningData
	 * @Description: 同步新系统的贷中数据(全量)
	 * @author 张庆奇
	 * @return void
	 * @throws @date
	 *             2016年9月21日 下午5:34:34
	 */
	public void saveLoaningDataAll() {
		int index = 0;
		while (index >= 0) {
			SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index, "select l.loanapply_no,wf_type,start_date from wf_type_status l where l.start_date is not null");
			PageResult<Object[]> pageResult = this.serviceDao.findDataWithPageForService(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] objs = pageResult.getData().get(i);
				BasicInformationLoanIng vo = new BasicInformationLoanIng();
				vo.setLoanapplyno(objs[0].toString());
				String type = objs[1].toString();
				Date date = DateUtils.formateStandDateTime(objs[2].toString());
				if ("ZX".equals(type)) {
					// 征信提交时间
					baseDao.excuteSql("update  basic_information_loan_ing set credit_reporting_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--征信提交时间：[{}]", vo.getLoanapplyno(), date);
				} else if ("NS".equals(type)) {
					// 内审提交时间
					baseDao.excuteSql("update  basic_information_loan_ing set in_exam_ing_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--内审提交时间：[{}]", vo.getLoanapplyno(), date);
				}
			}

			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}

		index = 0;
		while (index >= 0) {
			SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index, "select l.loanapply_no,wf_type,end_date from wf_type_status l where l.end_date is not null");
			PageResult<Object[]> pageResult = this.serviceDao.findDataWithPageForService(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] objs = pageResult.getData().get(i);
				BasicInformationLoanIng vo = new BasicInformationLoanIng();
				vo.setLoanapplyno(objs[0].toString());
				String type = objs[1].toString();
				Date date = DateUtils.formateStandDateTime(objs[2].toString());
				if ("ZX".equals(type)) {
					// 征信结束时间
					baseDao.excuteSql("update  basic_information_loan_ing set credit_over_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--征信结束时间：[{}]", vo.getLoanapplyno(), date);

				} else if ("NS".equals(type)) {
					// 内审结束时间
					baseDao.excuteSql("update  basic_information_loan_ing set in_exam_over_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--内审结束时间：[{}]", vo.getLoanapplyno(), date);

				} else if ("BRT".equals(type)) {
					// 银行送审结束时间
					baseDao.excuteSql("update  basic_information_loan_ing set bank_submit_over_date=? where loanapplyno=?", date, vo.getLoanapplyno());
					logger.info("新系统中的贷款数据（贷中）单号：[{}]--银行送审结束时间：[{}]", vo.getLoanapplyno(), date);

				}
			}

			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}

		// 银行放款时间

		List<Object[]> list = serviceDao.findParams("select da.loan_date ,ly.loanapply_no from o2o_loanapply ly left join o2o_bank_loan_data  da  on ly.bill_code = da.bill_code" + " where (ly.data_source IS NULL OR ly.data_source <> '2') AND da.loan_date is not null ");
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {

				Date date = DateUtils.formateStandDateTime(list.get(i)[0].toString() + " 00:00:00");
				String loanapplyno = list.get(i)[1].toString();
				baseDao.excuteSql("update  basic_information_loan_ing set bank_loan_date=? where loanapplyno=? ", date, loanapplyno);
				logger.info("新系统中的贷款数据（贷中）单号：[{}]--银行放款时间：[{}]", loanapplyno, date);
			}

		}

	}

	/**
	 * @Title: updateReportLoanIng
	 * @Description: 修改业务进度表
	 * @author 张庆奇
	 * @param sql
	 * @return void
	 * @throws @date
	 *             2016年12月30日 下午1:21:25
	 */
	public <T> void updateReportLoanIng(String sql) {
		int index = 0;
		int total = 0;
		String expsql = "update  report_loan_ing set credit_run_num=? ,credit_run_money=?, credit_pending_exam_num=? ,credit_pending_exam_money=?,in_exam_run_num=?,in_exam_run_money=? , exam_pending_bank_num=? ,exam_pending_bank_money=? where province_name=? and date(report_time) = curdate()";
		while (index >= 0) {
			SqlPageQuery<ReportLoanIng> sqlPageQuery = new SqlPageQuery<>(ReportLoanIng.class, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<ReportLoanIng> pageResult = this.serviceDao.findDataWithPageForService(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;

			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				ReportLoanIng obj = pageResult.getData().get(i);
				logger.debug("total:{},{}", ++total, obj.toString());
				try {
					baseDao.excuteSql(expsql, obj.getCreditRunNum(), obj.getCreditRunMoney(), obj.getCreditPendingExamNum(), obj.getCreditPendingExamMoney(), obj.getInExamRunNum(), obj.getInExamRunMoney(), obj.getExamPendingBankNum(), obj.getExamPendingBankMoney(), obj.getProvinceName());
				} catch (Exception e) {
					logger.error("数据库异常", e);

				}
			}

			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}

	}

	/**
	 * @Title: updateCreditData
	 * @Description: 修改征信失效状态，并且主单作废状态
	 * @author 张庆奇
	 * @param sql
	 * @param exeSql
	 * @return void
	 * @throws @date
	 *             2017年3月1日 上午10:17:34
	 */
	public void updateCreditData(String sql, String exeSql) {
		int index = 0;
		int total = 0;
		while (index >= 0) {
			SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<Object[]> pageResult = this.serviceDao.findDataWithPageForService(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;

			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] objs = pageResult.getData().get(i);

				logger.info("total:{},{}", ++total, objs);
				try {

					serviceDao.excuteSql(exeSql, objs[0]);

				} catch (Exception e) {
					logger.error("主键", objs[0]);
					logger.error("数据库异常", e);

				}
			}

		}

	}

	public List<Object[]> findObjectsList(String sql) {
		return serviceDao.findObjectsList(sql);
	}

	/**
	 * @Title: updateReportLoanIng
	 * @Description: 修改业务进度表（datasyn-10206 同步业务系统贷款流程统计（业务从库））
	 * @author GYH
	 * @param sql
	 * @return void
	 * @throws @date
	 *             2016年12月30日 下午1:21:25
	 */
	public <T> void updateReportLoanIngFromService(String sql) {
		int index = 0;
		int total = 0;
		String expsql = "update  report_loan_ing set credit_run_num=? ,credit_run_money=?, credit_pending_exam_num=? ,credit_pending_exam_money=?,in_exam_run_num=?,in_exam_run_money=? , exam_pending_bank_num=? ,exam_pending_bank_money=? where province_name=? and date(report_time) = curdate()";
		while (index >= 0) {
			SqlPageQuery<ReportLoanIng> sqlPageQuery = new SqlPageQuery<>(ReportLoanIng.class, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<ReportLoanIng> pageResult = this.serviceDao.findDataWithPageForService(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;

			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				ReportLoanIng obj = pageResult.getData().get(i);
				logger.debug("total:{},{}", ++total, obj.toString());
				try {
					serviceDao.excuteSql(expsql, obj.getCreditRunNum(), obj.getCreditRunMoney(), obj.getCreditPendingExamNum(), obj.getCreditPendingExamMoney(), obj.getInExamRunNum(), obj.getInExamRunMoney(), obj.getExamPendingBankNum(), obj.getExamPendingBankMoney(), obj.getProvinceName());
				} catch (Exception e) {
					logger.error("数据库异常", e);

				}
			}

			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}
	}
	
	

	/**
	 * @Title: cancelLoanapply
	 * @Description: 贷款申请超时作废
	 * @author 张庆奇
	 * @param sql
	 * @return void
	 * @throws
	 * @date 2017年8月15日 下午1:16:15
	 */
	public void cancelLoanapply(String sql) {
		List<O2oLoanapplyEntity> list = serviceDao.findEntitys(sql, O2oLoanapplyEntity.class);
		if (!list.isEmpty() && list.size() > 0) {

			for (O2oLoanapplyEntity entity : list) {

				String loapplyNo = entity.getLoanapplyNo();
				String type = entity.getWfType();
				ProcessTaskNode task = null;
				try {
					task = workflowService.getTaskNodeDetail(loapplyNo, "BANK_REPORT", "mq03");
				} catch (Exception e) {
					logger.error("单号：[{}]调用银行申报dubbo接口失败", loapplyNo);
					logger.error("错误日志", e);
					continue;
				}
				
				if (task == null) {
					common(loapplyNo, type);

				} 
//				else if (task.getNodeStatus() != ProcessTaskNode.NODE_STATUS_AUDIT_PASS) {
//					common(loapplyNo, type);
//				}
				logger.info("task：[{}]", task);
			}

		}

	}
	
	/**
	 * @Title: common
	 * @Description: 公共模快
	 * @author 张庆奇
	 * @param loapplyNo
	 * @param type
	 * @return void
	 * @throws
	 * @date 2017年8月29日 下午5:33:51
	 */
	public void common(String loapplyNo,String type){
		
		O2oCacleEntity cacle=new O2oCacleEntity();
		cacle.setLoanapplyNo(loapplyNo);
		cacle.settOperno("10000");
		cacle.settOpername("为系统自动作废");
		cacle.settTime(new Date());
		cacle.settType(type);
		cacle.settWhy("为贷款申请超时作废");
		cacle.settRemark("为贷款申请超时作废");
		cacle.settIsSuccess("N");
		cacle.settSysType("ST");//自动作废类型
		try {
			//1.作废表记录数据
			serviceDao.saveEntity(cacle);
			//2.作废单据和流程逻辑
			ModelResult<Boolean> modelResult=cancelService.worlFlowCancle(cacle);

			logger.error("作废单据返回消息", modelResult.getErrMsg());
		} catch (Exception e) {
			logger.error("作废单据调用远程服务", e);

		}
	}
	
/*	*//**
	 * @Title: invalidLoanLapply
	 * @Description: 作废单据和流程逻辑
	 * @author 张庆奇
	 * @param loapplyNo
	 * @return void
	 * @throws
	 * @date 2017年8月18日 上午9:09:07
	 *//*
	public void invalidLoanLapply(String loapplyNo) {
		Date date = new Date();
		String sql = "select * from o2o_loan_t_info where loanapply_no=? ORDER BY t_time desc limit 1";
		O2oCacleEntity cacleEntity =serviceDao.findEntity(sql, O2oCacleEntity.class, loapplyNo);
		O2oLoanapplyEntity loan = serviceDao.findById(O2oLoanapplyEntity.class,loapplyNo);
		boolean status ="NEW".equals(loan.getWfType()) ||"ZF".equals(loan.getWfType()) || "NF".equals(loan.getWfType());
		if (status) {
			
			if (StatusContexts.O2O_ZX_END.equals(loan.getWfType())|| StatusContexts.O2O_NEW.equals(loan.getWfType())) {
				O2oFinanceFlowEntity financeFlowEntity = serviceDao.findEntity("SELECT * FROM O2O_FINANCE_FLOW_STATUS WHERE LOANAPPLYNO=?", O2oFinanceFlowEntity.class, loapplyNo);
				if (null != financeFlowEntity && !StatusContexts.O2O_BANK_CLO.equals(financeFlowEntity.getFlowStatus())) {
					if (StatusContexts.O2O_BANK_RUN.equals(financeFlowEntity.getFlowStatus())) {
						CancleProcessParam cancleProcessParam = new CancleProcessParam();
						cancleProcessParam.setReferId(cacleEntity.getLoanapplyNo());
						cancleProcessParam.setOperName("为系统自动作废");
						cancleProcessParam.setOperNo("10000");
						cancleProcessParam.setCancleReason(cacleEntity.gettRemark());
						// 作废财务审核
						cacleEntity.settIsSuccess(StatusContexts.O2O_NO);
						cacleEntity.setId(UuidUtil.generateShortUuid());
						cacleEntity.settType(StatusContexts.WFTYPE_FINANCE);
						cacleEntity.settRemark("征信完成，作废单财务流程未作废，直接作废财务流程");
						serviceDao.saveEntity(cacleEntity);
						cancleProcessParam.setProcessType(ProcessTemplate.PROECESS_TYPE_FINANCE_AUDIT);
						cancelProcess(loan, cancleProcessParam, cacleEntity);
					}
					financeFlowEntity.setFlowStatus(StatusContexts.O2O_BANK_CLO);
					serviceDao.updateEntity(financeFlowEntity);
				}
			}
			
			loan.setWfType("T");
			loan.setEndDate(date);
			loan.setEndRo("为系统自动作废");
			int i = serviceDao.updateEntity(loan);
			if (i > 0) {
				cacleEntity.settIsSuccess("Y");
				serviceDao.updateEntity(cacleEntity);
				logger.info("作废单号：[{}]成功", loapplyNo);
				
				saveLog(loan.getBillCode(), "为系统自动作废",O2oLogType.LOAN_STATUS_T, loan.getEndDate(), cacleEntity.gettRemark(), "录入");
				
			} else {
				logger.info("作废单号：[{}]失败", loapplyNo);
			
			}
		} else {
			CancleProcessParam cancleProcessParam = new CancleProcessParam();
			cancleProcessParam.setReferId(cacleEntity.getLoanapplyNo());
			cancleProcessParam.setOperName("为系统自动作废");
			cancleProcessParam.setOperNo("10000");
			cancleProcessParam.setCancleReason(cacleEntity.gettRemark());
			// 征信中
			if (StatusContexts.LOAN_TYPE_BK.equals(loan.getLoanType()) && StatusContexts.O2O_ZX_BEGIN.equals(loan.getWfType())) {
				cancleProcessParam.setProcessType(ProcessTemplate.PROECESS_TYPE_CREDIT);
				ModelResult<Boolean> r = cancelProcess(loan, cancleProcessParam, cacleEntity);
				if (r.isSuccess()) {
					// 作废财务审核
					cacleEntity.settIsSuccess(StatusContexts.O2O_NO);
					cacleEntity.setId(UuidUtil.generateShortUuid());
					cacleEntity.settType(StatusContexts.WFTYPE_FINANCE);
					cacleEntity.settRemark("作废征信，直接作废财务流程");
					serviceDao.saveEntity(cacleEntity);
					cancleProcessParam.setProcessType(ProcessTemplate.PROECESS_TYPE_FINANCE_AUDIT);
					ModelResult<Boolean> r1 = cancelProcess(loan, cancleProcessParam, cacleEntity);
					if (r1.isSuccess()) {
						logger.info("作废单号：[{}]成功", loapplyNo);
					} else {
						logger.info("作废单号：[{}]失败", loapplyNo);
					}
				} else {
					logger.info("作废单号：[{}]失败", loapplyNo);
				}
			}
			if (StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType()) && StatusContexts.O2O_ZX_BEGIN.equals(loan.getWfType())) {
				cancleProcessParam.setProcessType(ProcessTemplate.PROECESS_TYPE_CREDI_BP);
				ModelResult<Boolean> r = cancelProcess(loan, cancleProcessParam, cacleEntity);
				if (r.isSuccess()) {
					logger.info("作废单号：[{}]成功", loapplyNo);
				} else {
					logger.info("作废单号：[{}]失败", loapplyNo);
				}
			}
			// 内审中
			if (StatusContexts.LOAN_TYPE_BK.equals(loan.getLoanType()) && StatusContexts.O2O_NS_BEGIN.equals(loan.getWfType())) {
				cancleProcessParam.setProcessType(ProcessTemplate.PROECESS_TYPE_INAUDIT);
				ModelResult<Boolean> r = cancelProcess(loan, cancleProcessParam, cacleEntity);
				if (r.isSuccess()) {
					logger.info("作废单号：[{}]成功", loapplyNo);
				} else {
					logger.info("作废单号：[{}]失败", loapplyNo);
				}
			}
			if (StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType()) && StatusContexts.O2O_NS_BEGIN.equals(loan.getWfType())) {
				cancleProcessParam.setProcessType(ProcessTemplate.PROECESS_TYPE_INAUDIT_BP);
				ModelResult<Boolean> r = cancelProcess(loan, cancleProcessParam, cacleEntity);
				if (r.isSuccess()) {
					logger.info("作废单号：[{}]成功", loapplyNo);
				} else {
					logger.info("作废单号：[{}]失败", loapplyNo);
				}
			}
			// 申报中
			if (StatusContexts.O2O_SB_BEGIN.equals(loan.getWfType())) {
				cancleProcessParam.setProcessType(ProcessTemplate.PROECESS_TYPE_BANK_REPORT);
				ModelResult<Boolean> r = cancelProcess(loan, cancleProcessParam, cacleEntity);
				if (r.isSuccess()) {
					logger.info("作废单号：[{}]成功", loapplyNo);
				} else {
					logger.info("作废单号：[{}]失败", loapplyNo);
				}
			}
		}
		
	}
	
	*//**
	 * @Title: cancelProcess
	 * @Description: 作废工作流流程
	 * @author 张庆奇
	 * @param loan
	 * @param cancleProcessParam
	 * @param cacleEntity
	 * @return
	 * @return ModelResult<Boolean>
	 * @throws
	 * @date 2017年8月18日 上午9:29:39
	 *//*
	public ModelResult<Boolean> cancelProcess(O2oLoanapplyEntity loan, CancleProcessParam cancleProcessParam,
			O2oCacleEntity cacleEntity) {
		ModelResult<Boolean> model = workflowService.cancelProcess(cancleProcessParam);
		if (model.isSuccess()) {
			if (!StatusContexts.WFTYPE_FINANCE.equals(cacleEntity.gettType())) {
				loan.setWfType(StatusContexts.O2O_FK_OVER);
				loan.setEndDate(new Date());
				loan.setEndRo("10000");
				serviceDao.updateEntity(loan);
				// 更新作废记录表状态
				cacleEntity.settIsSuccess(StatusContexts.O2O_YES);
				serviceDao.updateEntity(cacleEntity);
				logger.info("工作流关闭单号为：{} 流程成功", loan.getLoanapplyNo());
			}
		} else {
			logger.info("工作流关闭单号为：{} 流程失败", loan.getLoanapplyNo());
		}
		return model;
	}
	@Transactional(transactionManager = "o2oTransactionManager")
	public void saveLog(String billCode, String opPsn, String type, Date settleDate, String remark, String motion) {
		// 保存作废操作日志
		O2oRecordLog log = new O2oRecordLog();
		try {
			log.setBillCode(billCode);
			log.setOpPsn(opPsn);
			log.setOpDate(new Date());
			log.setOpType(type);
			log.setOpTypeName(O2oLogType.getStringName(type));
			log.setSettleDate(settleDate);
			log.setRemark(remark);
			log.setMotion(motion);

			serviceDao.saveEntity(log);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	
	
}
